import os
import csv
import sys
import logging
import datetime
from odps import ODPS
"""
导出订单
city_id
prod_cate_cd
out_channel==1 or out_channel==2 天猫单
"""
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d: %(message)s')
logger = logging.getLogger(__name__)

def get_yesterday(day_num=1, day_format="%Y-%m-%d"):
    today = datetime.date.today()
    oneday = datetime.timedelta(days=day_num)
    yesterday = today - oneday
    return yesterday.strftime(day_format)


if __name__ == '__main__':
    try:
        day_interval = int(sys.argv[1])
    except:
        day_interval = 1
    if day_interval < 1:
        day_interval = 1
    select_day = get_yesterday(day_interval, '%Y%m%d')
    save_day = get_yesterday(day_interval)
    target_dir = "/data/disp/" + save_day + "/"
    try:
        os.makedirs(target_dir)
    except:
        pass
    target_file = target_dir + "orders.csv"
    if not os.path.exists(target_file):
        # 这里替换成你自己的存储连接
        odps = ODPS('xxx', 'xxxxxxxxxxx', 'XXX_APP', endpoint='http://service.odps.aliyun.com/api')
        # 这里替换成你自己的订单
        order_sql = """
        select o.order_seq,o.artisan_id,o.city_id,o.prod_cate_cd,o.create_tm,o.reserve_tm,o.srv_addr,o.out_channel,
          p.prod_minute,
          a.longitude as artisan_lon,a.latitude as artisan_lat,a.addr,
          tt.lock_hour, tt.positions
           from xxx_ods.dws_order_union o 
        left join xxx_ods.dw_ar_artisan_product p on o.prod_id=p.prod_id
        left join xxx_ods.dws_su_artisan_ext a on o.artisan_id=a.artisan_id
        left join
        (
        select o.order_seq, abs(replace(split(t.positions, ",")[0],"#1","")) as lock_hour, t.positions from xxx_ods.ods_s02_inventory_time_lock t 
        left join xxx_ods.dws_srv_performance_order o on t.lock_scope_id=o.performance_seq
        where t.lock_scope=1 and t.ds='%s' and o.ds='%s'
        ) tt on o.order_seq=tt.order_seq
         where o.order_status_cd='10' and substr(o.reserve_tm, 1, 10)='%s' and o.ds='%s' and p.ds='29991231' and a.ds='%s'
        """ % (select_day, select_day, save_day, select_day, select_day)

        with odps.execute_sql(order_sql).open_reader() as reader:
            result_df = reader.to_pandas()

        if result_df is not None and len(result_df) > 0:
            result_df.to_csv(target_file, quoting=csv.QUOTE_ALL)
            print('export orders:' + str(len(result_df)))
